package com.xiaomaoguai.curator.common.zookeeper.server;

import com.xiaomaoguai.curator.common.model.Model;
import com.xiaomaoguai.curator.common.conf.ServerConfig;
import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Set;

/**
 * @fileName: ServerSideZkThread.java
 * @author: WeiHui.Zhang
 * @date: 2016-11-05  15:12
 * @version: v1.0.0
 */
public class ServerSideZkThread implements Runnable {

	private Logger LOGGER = LoggerFactory.getLogger(ServerSideZkThread.class);

	private Set<Model> modelSet;
	private ServerConfig config;

	public ServerSideZkThread(Set<Model> modelSet, ServerConfig config) {
		this.modelSet = modelSet;
		this.config = config;
	}

	@Override
	public void run() {
		String name = Thread.currentThread().getName();
		LOGGER.info("current running thread :" + name);

		RetryPolicy retryPolicy = new ExponentialBackoffRetry(1000, Integer.MAX_VALUE);

		CuratorFramework curatorFramework = CuratorFrameworkFactory.builder() //
				.connectString(config.zkClusterAddress()) //  连接zookeeper的地址
				.sessionTimeoutMs(config.sessionTimeoutMs())  //session 超时时间
				.connectionTimeoutMs(config.connectionTimeoutMs()) // 连接超时时间
				.retryPolicy(retryPolicy)  //重试策略
				.build();

		ServerSideZkConnectionStateListener listener = new ServerSideZkConnectionStateListener(modelSet);

		curatorFramework.getConnectionStateListenable().addListener(listener);

		curatorFramework.start();

	}
}
